package com.guanyu.u2cache.config;

import com.guanyu.u2cache.constant.ExcuConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Description :自定义线程池
 *
 * @author zgy
 * Date 2021/6/18
 * todo 根据不同操作系统的cpu个数，做初始化设置，后续优化处理
 */
@Slf4j
@Configuration
@EnableAsync
public class PreloadThreadPoolConfiguration {

    /**
     * 线程池初始大小
     **/
    @Value("${preLoad.corePoolSize:5}")
    private int coreNum;
    /**
     * 线程池最大值
     **/
    @Value("${preLoad.maxPoolSize:30}")
    private int maxNum;
    /**
     * 等待时间
     **/
    @Value("${preLoad.keepAliveTime:60}")
    private int keepAliveTime;
    /**
     * 等待队列长度
     **/
    @Value("${preLoad.blockqueue.size:20}")
    private int blockQueueLength;


    @Bean(ExcuConfig.name)
    public ThreadPoolExecutor loadExecutor() {
        log.info("预加载线程池启动开始");
        ThreadPoolExecutor executor = new ThreadPoolExecutor(coreNum, maxNum, keepAliveTime,
                TimeUnit.SECONDS, new LinkedBlockingDeque<>(blockQueueLength), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());
        log.info("预加载线程池启动结束");
        return executor;
    }
}
